import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore(
  'user',
  () => {
    // 状态
    const token = ref(localStorage.getItem('token')||'')
    const role = ref(localStorage.getItem('role')||'')

    // 设置 token（自动添加 Bearer 前缀）
    const setToken = (newToken) => {
      token.value = newToken.startsWith('Bearer ') ? newToken : `Bearer ${newToken}`
      localStorage.setItem('token', token.value)
    }

    // 清除 token
    const removeToken = () => {
      token.value = ''
      localStorage.removeItem('token')
    }

    // 设置 role
    const setRole = (roleValue) => {
      role.value = roleValue
      localStorage.setItem('role', roleValue)
    }

    // 清除 role
    const removeRole = () => {
      role.value = ''
      localStorage.removeItem('role')
    }

    const user = ref(JSON.parse(localStorage.getItem('user') || '{}')) // 读取并解析 user 对象

    const setUser = (userObj) => {
      user.value = userObj
      localStorage.setItem('user', JSON.stringify(userObj))
    }

    // 清除用户信息
    const removeUser = () => {
      user.value = null
      localStorage.removeItem('user')
    }

    // 获取用户信息（示例实现）
    const getUser = async () => {
      // 实际项目中这里应该是 API 调用
      return user.value
    }

    // 清除所有用户状态
    const clearAll = () => {
      removeToken()
      removeRole()
      removeUser()
    }

    return {
      token,
      role,
      user,
      setToken,
      removeToken,
      setRole,
      removeRole,
      setUser,
      removeUser,
      getUser,
      clearAll
    }
  },
  {
    persist: {
      key: 'user',
      storage: localStorage,
      serializer: {
        serialize: JSON.stringify,
        deserialize: (str) => {
          try {
            return JSON.parse(str);
          } catch (e) {
            console.error('解析存储数据失败，返回默认值');
            return { token: '', userInfo: null }; // 返回默认状态
          }
        },
      },
    },
  },
)
